<script setup lang="tsx">
import { computed, onMounted, ref } from 'vue';
import type { JSX } from 'vue/jsx-runtime';
import { closeToast } from 'vant';
import { PtPage, useSourceLoading } from './modules/pt-page';
import { debounce, tryit, throttle } from 'radash';
import { getBookletShader, getBookletShaderFromStudent, type OriginData } from './api';

const pt = ref<PtPage>();
const box = ref<HTMLElement>();
const rendered = ref<JSX.Element>();

const render = debounce({ delay: 600 }, () => {
  rendered.value = pt.value!.render();
});

const { setCurrent, setCount, renderMessage, closeMessage } = useSourceLoading(() => {
  render();
  closeToast();

  window.addEventListener('resize', debounce({ delay: 300 }, () => {
    render();
  }));
});

const main = async (createdId: string, data: OriginData) => {
  const [error, shader] = await ('dataToken' in data ? tryit(getBookletShader)(createdId, data) : tryit(getBookletShaderFromStudent)(createdId, data));

  if (error) {
    console.error('读取错误', error);
    return;
  }

  document.title = `${shader.title || ''} - ${shader.data.org.name || ''}`
  pt.value = new PtPage(shader, shader.data);

  pt.value.preloadSources((current, total) => {
    setCount(total);
    setCurrent(current);
    renderMessage();
  }).then(() => {
    closeMessage();
  })
}

onMounted(() => {
  const params = new URLSearchParams(location.search);
  const createdId = params.get('id') || '';
  const pw = params.get('pw') || '';

  // 公开查看
  // https://t.shijiwxy.5tree.cn/eduGrowth/wxy/booklet/index.html?id=119&pw=39a0b5a7112237f9e8304182022d1d0e
  if (createdId && pw) {
    main(createdId, {
      dataToken: pw
    });
    return;
  }

  // 登录角色查看
  // https://t.shijiwxy.5tree.cn/eduGrowth/wxy/booklet/index.html?id=119
  const studentJson = sessionStorage.getItem('nowStudent');
  const baseJson = sessionStorage.getItem('baseUser');

  if (studentJson && baseJson) {
    try {
      const base = JSON.parse(baseJson);
      const student = JSON.parse(studentJson);

      if (student) {
        main(createdId, {
          userId: String(student.user_id),
          name: student.stud_name,
          token: base.token,
          udid: base.udid
        });
        return;
      }
    } catch (error) {
      console.error('读取错误', error);
    }
  }

  // 无效查看
  console.log('无效查看');
});

const pageStyle = computed(() => {
  return {
    '--page-width': (pt.value?.performance.width || '0') + 'px',
    '--page-height': (pt.value?.performance.height || '0') + 'px',
  };
});
</script>

<template>
  <div ref="box" class="boxer" :style="pageStyle">
    <component v-if="rendered" :is="rendered" />
  </div>
</template>

<style scoped></style>
